﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MVCms.Core.Developers;
using MVCms.Core.Entities;
using MVCms.Core.Services;
using Plugin.Admin.PageManager.Models;


namespace Plugin.Admin.PageManager.Controllers
{
    public class PageManagerController : BaseController
    {
        [PluginModule(Name = "AddPage", Description = "AddPage", DisplayName = "AddPage", PostController = "PageManager", PostAction = "AddPage")]
        [HttpGet]
        public PartialViewResult AddPage()
        {
            PageManagerModel model = new PageManagerModel();
            IEnumerable<VirtualPage> virtualPages = PageService.GetPages();
            model.ParentPages = virtualPages;
            model.EnableHyperlink = true;
            model.VisibleInMenu = true;

            return PartialView(model);
        }

        [HttpPost]
        public PartialViewResult AddPage(PageManagerModel model)
        {
            if (ModelState.IsValid)
            {
                VirtualPage page = new VirtualPage
                                       {
                                           Name = model.Name,
                                           Title = model.Title,
                                           EnableHyperlink = model.EnableHyperlink,
                                           Parent = MVCms.Core.Services.PageService.GetPage(model.ParentPage),
                                           Visible = model.VisibleInMenu,
                                           Status = Status.Active
                                       }.Save();

                RouteTable.Routes.Insert(0, new Route(page.Url.TrimStart('/'), new MvcRouteHandler())
                                                {
                                                    Defaults = new RouteValueDictionary(new
                                                                                            {
                                                                                                controller = "Page",
                                                                                                action = "Index"
                                                                                            })
                                                });
            }
            else
            {
                ModelState.AddModelError("", "Please correct the errors and try again");
            }

            return PartialView(model);
        }
    }
}
